<template>
  <my-dialog :title="title"
             :width="width"
             :height="height"
             :visible="visible"
             @onClose="handleCancel"
             @onConfirm="handleConfirm"
  >
    <template v-slot:content>
      <el-form
        :model="dialog.form"
        ref="dialogFormRef"
        :rules="rules"
        label-width="auto"
        size="default"
      >
        <el-form-item prop="name" label="部门名称">
          <el-input v-model="dialog.form.name"></el-input>
        </el-form-item>
        <el-form-item prop="location" label="部门所在地">
          <el-input v-model="dialog.form.location"></el-input>
        </el-form-item>
      </el-form>
    </template>
  </my-dialog>
</template>

<script setup lang="ts">
import MyDialog from '@/components/global/MyDialog.vue'
import { onMounted, reactive, ref, toRefs, unref, } from 'vue'
import type { FormInstance } from 'element-plus'
import { emitter, useDepartmentStore } from '@/stores/department.store.ts'
import { storeToRefs } from 'pinia'
import { DialogType } from '@/stores/department.store.type.ts'
import { useDepartmentDialog } from '@/hooks/department.hook.ts'

const store = useDepartmentStore()
const { dialog } = storeToRefs(store)
const {
  title, width, height, visible
} = toRefs(dialog.value)

const {
  closeDialog,
  showDialogForAdd, showDialogForUpdate,
  submitFormForAdd, submitFormForUpdate,
} = useDepartmentDialog()


const dialogFormRef = ref<FormInstance>()

// 表单验证规则
const rules = reactive({
  name: [{
    required: true,
    trigger: 'change',
    message: '请填写部门名称'
  }]
})

const handleCancel = closeDialog

function handleConfirmForAdd() {
  submitFormForAdd().then((res) => {
    if (res && res.code == 200)
      emitter.emit('dialog_department_added')
  })
}

function handleConfirmForUpdate() {
  submitFormForUpdate().then((res) => {
    if (res && res.code == 200)
      emitter.emit('dialog_department_updated')
  })
}

function handleConfirm() {
  console.info(unref(dialog).type)
  dialogFormRef.value?.validate(async (valid) => {
    if (valid) {
      if (dialog.value.type == DialogType.Add) {
        handleConfirmForAdd()
      } else if (dialog.value.type == DialogType.Update) {
        handleConfirmForUpdate()
      } else {
        console.info('logical error')
      }
      closeDialog()
    }
  })
}

onMounted(() => {
  emitter.on('search_add_btn_clicked', () => {
    dialogFormRef.value?.resetFields()
    showDialogForAdd()
  })
  emitter.on('table_edit_btn_clicked', () => {
    dialogFormRef.value?.resetFields()
    showDialogForUpdate()
  })
})

</script>


<style scoped lang="scss">

</style>
